package com.atguigu.test.processor;

import com.atguigu.test.po.A;
import com.atguigu.test.po.AutowiredAnnotationBean;
import com.atguigu.test.po.LifeCycleBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor;
import org.springframework.beans.factory.annotation.InjectionMetadata;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.ContextAnnotationAutowireCandidateResolver;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.util.StringValueResolver;

import java.lang.reflect.Method;

/**
 * @author zp
 * @version 1.0
 * @description: 解析AutowiredAnnotationBeanPostProcessor的参数
 * @date 2022/12/15 20:17
 */
@Slf4j
public class MyAutowiredAnnotationBeanPostProcessor {
    public static void main(String[] args) throws Throwable {
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        factory.registerSingleton("a", A.class);
        factory.registerSingleton("lifeCycleBean", LifeCycleBean.class);

        // 配置一个Autowire 后置解析器
        factory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
        factory.addEmbeddedValueResolver(new StandardEnvironment()::resolvePlaceholders);

        // 未注入AutowiredAnnotationBeanPostProcessor 之前的参数
        AutowiredAnnotationBean autowiredAnnotationBean = new AutowiredAnnotationBean();
        log.info("未注入AutowiredAnnotationBeanPostProcessor autowiredAnnotationBean的信息：[{}]",autowiredAnnotationBean);
        // 手动注入一个AutowiredAnnotationBeanPostProcessor解析器 执行解析Autowired注解的后置处理器
        AutowiredAnnotationBeanPostProcessor autowiredAnnotationBeanPostProcessor = new AutowiredAnnotationBeanPostProcessor();
        autowiredAnnotationBeanPostProcessor.setBeanFactory(factory);
        // autowiredAnnotationBeanPostProcessor.postProcessProperties(null,autowiredAnnotationBean,"autowiredAnnotationBean");

        Method findAutowiringMetadata = AutowiredAnnotationBeanPostProcessor.class.getDeclaredMethod("findAutowiringMetadata", String.class, Class.class, PropertyValues.class);
        findAutowiringMetadata.setAccessible(true);
        InjectionMetadata injectionMetadata = (InjectionMetadata)findAutowiringMetadata.invoke(autowiredAnnotationBeanPostProcessor, "autowiredAnnotationBean", AutowiredAnnotationBean.class, null);
        log.info("测试打印对象：[{}]",injectionMetadata);

        injectionMetadata.inject(autowiredAnnotationBean,"autowiredAnnotationBean",null);
        log.info("已注入AutowiredAnnotationBeanPostProcessor autowiredAnnotationBean的信息：[{}]",autowiredAnnotationBean);


    }
}
